package models

import (
	"demo02/settings"
	"github.com/jinzhu/gorm"
	"log"
	"strconv"
)

var db *gorm.DB

type Plan struct {
	Id          int    `gorm: "primary_key" json:"id"`
	CompanyCode string `json:"company_code"`
	Name        string `json:"name"`
}

var DbConnection string

func FindPlans(pageIndex int, pageSize int) ([]*Plan, error) {
	var plans []*Plan
	err := db.Offset(pageIndex-1).Limit(pageSize).Find(&plans).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return plans, nil
}

func FirstPlan() *Plan {
	var plan = Plan{}
	db.First(&plan)
	return &plan
}

func Setup() {
	DbConnection = settings.GlobalConfig.Db.Username + ":" + settings.GlobalConfig.Db.Password +
		"@tcp(" + settings.GlobalConfig.Db.Host + ":" + strconv.Itoa(settings.GlobalConfig.Db.Port) + ")/" +
		settings.GlobalConfig.Db.Database + "?parseTime=True"

	var err error
	db, err = gorm.Open("mysql", DbConnection)
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		log.Printf("tablename: %v", defaultTableName)
		if defaultTableName == "plan" {
			return "eam_core_patrol_plan"
		}
		return defaultTableName
	}
	if err != nil {
		log.Fatalf("model setup err: %v", err)
	}

	db.SingularTable(true)
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)
}
